﻿using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using System.Threading.Tasks;
#if NETCOREAPP3_0
using Microsoft.AspNetCore.Routing;
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
#elif NETSTANDARD2_0
using Newtonsoft.Json;
#endif

namespace Microsoft.AspNetCore.Builder
{
    /// <summary>
    /// BootstrapAdmin 健康检查扩展类
    /// </summary>
    public static class HealthChecksBuilderExtensions
    {
#if NETCOREAPP3_0
        /// <summary>
        /// 启用健康检查
        /// </summary>
        /// <param name="endpoints"></param>
        /// <param name="path"></param>
        /// <param name="configure"></param>
        /// <returns></returns>
        public static IEndpointRouteBuilder MapBootstrapHealthChecks(this IEndpointRouteBuilder endpoints, PathString path = default, Action<HealthCheckOptions> configure = null)
        {
            if (path == default) path = "/Healths";
            var option = new HealthCheckOptions()
            {
                ResponseWriter = (context, report) =>
                {
                    context.Response.ContentType = "application/json";

                    // 修复 TimeSpan
                    var serializeOption = new JsonSerializerOptions();
                    serializeOption.Converters.Add(new StringToTimeSpanConverter());
                    return context.Response.WriteAsync(JsonSerializer.Serialize(new { report.Entries.Keys, Report = report }, serializeOption));
                },
                ResultStatusCodes =
                {
                    [HealthStatus.Healthy] = StatusCodes.Status200OK,
                    [HealthStatus.Degraded] = StatusCodes.Status200OK,
                    [HealthStatus.Unhealthy] = StatusCodes.Status200OK
                }
            };
            configure?.Invoke(option);
            endpoints.MapHealthChecks(path, option);
            endpoints.MapGet("/healths-ui", context =>
            {
                context.Response.Redirect("/html/Healths-UI.html");
                return Task.CompletedTask;
            });
            return endpoints;
        }
#elif NETSTANDARD2_0
        /// <summary>
        /// 启用健康检查
        /// </summary>
        /// <param name="app"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseBootstrapHealthChecks(this IApplicationBuilder app, PathString path = default)
        {
            if (path == default) path = "/Healths";
            app.UseHealthChecks(path, new HealthCheckOptions()
            {
                ResponseWriter = (context, report) =>
                {
                    context.Response.ContentType = "application/json";
                    return context.Response.WriteAsync(JsonConvert.SerializeObject(new { report.Entries.Keys, Report = report }));
                },
                ResultStatusCodes =
                {
                    [HealthStatus.Healthy] = StatusCodes.Status200OK,
                    [HealthStatus.Degraded] = StatusCodes.Status200OK,
                    [HealthStatus.Unhealthy] = StatusCodes.Status200OK
                }
            });
            app.UseWhen(context => context.Request.Path == "/healths-ui", builder => builder.Run(request =>
            {
                request.Response.Redirect("/html/Healths-UI.html");
                return Task.CompletedTask;
            }));
            return app;
        }
#endif
    }
}
